/*
 * Trim filter processor
 *
 * Copyright (C) 2006 Igor Popik <thrull@bezsensu.pl> -  www.thrull.com
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * $Id: trim_processor.c,v 1.8 2006/09/05 09:38:48 thrull Exp $
 */

#ifdef MCC_HTTPD
#include "nsapi.h"
#endif

#include "trim_processor.h"

#include <string.h>

int trim(trim_state * s, char *data, int len)
{
        int count = 0;
        int i;
        char c;

        for (i = 0; i < len; i++) {
                c = data[i];

                switch (c) {
                case 13:
                case 10:
                case 9:
                case 32:
                        if (s->forbidden) {
                            data[count++] = c;
                        } else if (!s->empty) {
                            data[count++] = c;
                            s->empty = 1;
                        }
                        break;
                case '<':
                        if (((i + 3 < len) && !strncasecmp(data + i + 1, "pre", 3)) ||
                             ((i + 8 < len) && !strncasecmp(data + i + 1, "textarea", 8))) {
                                s->forbidden = 1;
                        } else if (s->forbidden)
                                if (((i + 4 < len) && !strncasecmp(data + i + 1, "/pre", 4)) ||
                                    ((i + 9 < len) && !strncasecmp(data + i + 1, "/textarea", 9))) {
                                        s->forbidden = 0;
                                }
                default:
                        data[count++] = c;
                        s->empty = 0;
                        break;
                }
        }
        data[count] = 0;
        return count;
}

